package com.boot.mall.seckill.interceptor;

import com.boot.common.constant.AuthConstant;
import com.boot.common.vo.MemberResponseVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 秒杀登录拦截
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberResponseVo> memberInfo = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取session
        HttpSession session = request.getSession();
        MemberResponseVo attribute = (MemberResponseVo) session.getAttribute(AuthConstant.LOGIN_USER);
        // 请求路径
        String uri = request.getRequestURI();
        boolean match = new AntPathMatcher().match("/seckill/**", uri);
        if (match){
            // 当路径匹配时，拦截没有登录的用户信息
            if (attribute == null){
                response.sendRedirect("redirect:http://auth.guli.com/login.html");
                return false;
            }
            // 用户已登录
            memberInfo.set(attribute);
        }
        // 放行
        return true;
    }
}
